﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Threading;
using Test;
namespace EvLog {
	static class EvLog {
		public static SQL local=new SQL();
		static void MainX() {
			List<string> MachineNames=new List<string>();
			//MachineNames.AddRange(Mixer.Combine("pon-wpwb0{0}-cl0{1}","3","1,2"));
			//MachineNames.AddRange(Mixer.Combine("pon-wpas10-cl0{0}","1,2"));
			//MachineNames.AddRange(Mixer.Combine("pon-wprf0{0}-cl0{1}","1,2,3,4","1,2"));
			//MachineNames.AddRange(Mixer.Combine("pon-wpwb0{0}-cl0{1}","1,2,3","1,2"));
			//MachineNames.AddRange(Mixer.Combine("pon-wpsq{0}-cl0{1}","01,02,03,04,06,07,08,09,10,11,12,13,15,16","1,2"));
			//MachineNames.AddRange(Mixer.Combine("pon-wpct{0}","51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70"));
			//MachineNames.Add("PON-WPAS10-cl01");
			//MachineNames.Add("PON-WPAS10-cl02");
			MachineNames.Add("PON-WPsq10-cl01");
			MachineNames.Add("PON-WPsq10-cl02");
			//local.NonQry("truncate table elog");
			List<Thread> thLst=new List<Thread>();
			foreach(string machine in MachineNames)
				thLst.Add(new Thread(new LogReader(machine).Read));
			foreach(Thread th in thLst)
				th.Start();
			foreach(Thread th in thLst)
				th.Join();
			Console.WriteLine("THE END");
		}
	}
	class LogReader {
		string format="insert into elog(cat,eType,machine,src,eTime,usr,msg)values('{0}','{1}','{2}','{3}',convert(datetime,'{4}',120),'{5}','{6}')";
		string _machine;
		public LogReader(string machine) { _machine=machine; }
		public void Read() {
			EventLog[] logs=EventLog.GetEventLogs(_machine);
			foreach(EventLog log in logs)
				if(log.Log.ToLower()=="application")
					for(int i=log.Entries.Count-1;i>=0;i--)
					{
						EventLogEntry ent=log.Entries[i];
						//if(ent.TimeWritten.Date.AddDays(1)<DateTime.Now.Date)
						//if(ent.TimeWritten<DateTime.Now.AddHours(-12))
						if(ent.TimeWritten<DateTime.Now.AddDays(-1))
							break;
						//if(ent.Message.Contains("transport-level"))
						//if(ent.Message.Contains("does not have an implementation"))
						//if(ent.Source=="Next.Whs.ReturnsService2")
						if(ent.EntryType==EventLogEntryType.Error)
							EvLog.local.NonQry(string.Format(format,ent.Category,ent.EntryType,ent.MachineName,ent.Source,ent.TimeGenerated.ToString("yyyy-MM-dd HH:mm:ss"),ent.UserName,ent.Message.Replace("'","''")));
					}
			Console.WriteLine(_machine);
		}
	}
}

/*
drop table elog
create table elog(
id int identity,
cat varchar(255),
eType varchar(25),
machine varchar(50),
src varchar(255),
eTime datetime,
usr varchar(50),
msg varchar(max),
constraint pk_elog_id primary key(id)
)
create index ix_elog_eTime on elog(eTime)
*/






